package com.project;

import com.project.servlet.TestServlet;
import com.project.servlet.student.AddServlet;
import com.project.servlet.student.CutAllServlet;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.servlet.Servlet;

public class Main {
    public Main() {
        //创建Tomcat容器对象
        Tomcat tomcat = new Tomcat();
        //设置启动端口
        tomcat.setPort(8088);
        //引导http引擎
        tomcat.getConnector();

        AnnotationConfigApplicationContext springContext =
                new AnnotationConfigApplicationContext(MyBatisConfig.class);

        //得到web上下文全局对象
        Context webContext = tomcat.addContext("",null);

        this.registerServlet(webContext,springContext.getBean(CutAllServlet.class),"/cutAll");
        this.registerServlet(webContext,new TestServlet(),"/test");
        this.registerServlet(webContext,new AddServlet(),"/add");

        try {//启动tomcat
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new Main();
    }

    private void registerServlet(Context webContext, Servlet servletObj,String url){
        //注册servlet类，第一个参数为上下文对象 //第二个参数为servlet名称，第三个参数为servlet对象
        Wrapper w = Tomcat.addServlet(webContext,servletObj.getClass().getName(),servletObj);
        //配置servlet的客户端访问路径
        w.setLoadOnStartup(0);
        w.addMapping(url);
    }

}
